<template>
	<view>
		<uv-toast ref="toast"></uv-toast>
		<!-- 加载组件 -->
		<PLoader :loading="loading" backgroundColor="#00000065"></PLoader>
		<!-- 错误提示 -->
		<view class="error-tip" :class="{ 'show': showError }">
			<text class="error-text">{{ errorMessage }}</text>
		</view>
		<VideoPayCoursePlayer :playInfoList="videoInfo.definitions" :videoCover="videoInfo.coverUrl"
			:adList="playerAdList" :videoTitle="videoInfo.title" @error="handleError" @play="handlePlay"
			@pause="handleVideoPause" @timeupdate="handleTimeUpdate" :curCourseMediaId="curCourseMedia.id"
			:historyProgress="historyProgress" @ended="handleEnded">
		</VideoPayCoursePlayer>

		<view class="history" v-if="mediaHistory.progress && !mediaHistory.completed">
			<view v-if="!loading">
				<view class="first">
					<text class="title">上次观看至: <text style="color: #3c9cff;">
							{{ formatTime(mediaHistory.progress) }}</text></text>
					<view class="button" @click="restoreHistory">
						<text>继续观看</text>
					</view>
				</view>
				<uv-line-progress :percentage="mediaHistory.watchPercent" :show-text="false" active-color="#3c9cff" />
			</view>
			<uv-loading-icon :show="loading" color="#3c9cff" mode="semicircle" size="32"></uv-loading-icon>
		</view>

		<!-- 课程信息展示区 -->
		<view class="course-info-container">
			<!-- 毛玻璃背景 -->
			<view class="glass-bg"></view>

			<!-- 内容包装器 -->
			<view class="content-wrapper">
				<!-- 主要信息 -->
				<view class="main-info">
					<view class="title-section">
						<text class="title">{{ videoInfo.title }}</text>
						<view class="tags">
							<text v-for="(tag, index) in courseInfo.parseTags" :key="index" class="tag">{{ tag }}</text>
						</view>
					</view>
				</view>

				<!-- 视频信息 -->
				<view class="video-info">
					<view class="info-item">
						<text class="icon-duration"></text>
						<text class="label">时长：</text>
						<text class="value">{{ formatDuration(videoInfo.duration) }}</text>
					</view>
					<view class="info-item">
						<text class="icon-quality"></text>
						<text class="label">清晰度：</text>
						<text class="value">{{ getHighestQuality() }}</text>
					</view>
				</view>
				<text class="video-des">{{ videoInfo.description }}</text>

				<VideoChapters :courseMedias="courseMediaList" :curMediaId="curCourseMedia.id"
					@chaptersClick="handleChpatersSwithch"></VideoChapters>

				<!-- 课程描述 -->
				<view class="description">
					<view class="info">
						<view class="course-cover">
							<image class="cover" :src="courseInfo.image" />
						</view>
						<view class="des">
							<text class="course-name">{{ courseInfo.name }}</text>
							<text class="desc-title">课程简介</text>
						</view>
					</view>
					<text class="desc-content">{{ courseInfo.description }}</text>
				</view>

				<!-- 课程状态信息 -->
				<view class="status-info">
					<view class="status-item">
						<uv-icon name="calendar" size="36" color="#23666"></uv-icon>
						<text>上线时间：{{ formatDate(courseInfo.onlineDate) }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 页面广告列表 -->
		<view class="page-ads-container">
			<view class="ad-item" v-for="ad in pageAdList" :key="ad.id" @tap="handleAdClick(ad)">
				<image :src="ad.imageUrl" mode="aspectFill" class="ad-image"></image>
				<view class="ad-info">
					<text class="ad-title">{{ ad.title }}</text>
					<text class="ad-desc">{{ ad.description }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import debounce from '../../uni_modules/uv-ui-tools/libs/function/debounce';
	import {
		formatDate
	} from '@/utils/timeParse.js';
	export default {
		data() {
			return {
				loading: false,
				showError: false,
				errorMessage: '',
				errorTimer: null,
				courseId: 0,
				courseInfo: {},
				pageSize: 6,
				pageNumber: 1,
				courseMediaList: [],
				totalMedia: 0,
				curCourseMedia: {},
				videoInfo: {
					id: null,
					title: '',
					videoUrl: '',
					coverUrl: '',
					views: 0,
					createTime: '',
					description: '',
					duration: '',
					status: '',
					mediaType: '',
					definition: '',
					definitions: [],
					bitrate: '',
					size: 0,
				},
				adList: [],
				playerAdList: [],
				pageAdList: [],
				pageNum: 1,
				hasMore: true,
				isLoading: false,
				watchProgress: 0,
				progressSaveThrottle: null,
				mediaHistory: {},
				historyProgress: 0,
			};
		},

		methods: {
			showToast(msg, type = 'default', duration = 1000) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			// 处理章节切换
			async handleChpatersSwithch(item) {
				await this.fetchCourseMedia(item.id);
				await this.fetchCurMediaHitory(item.id);
				uni.$emit('chpatersSwithch');
			},
			// 播放完成事件
			async handleEnded() {
				try{
					const data = await this.$http.post('/user/video/pay/complete', this.curCourseMedia);
				}catch(e){
					console.error('播放完成执行失败', e);
				}
			},
			// 恢复历史记录
			restoreHistory() {
				this.historyProgress = this.mediaHistory.progress;
				this.mediaHistory = {};
			},
			// 处理视频播放进度 视频进度节流保存
			handleTimeUpdate(e) {
				if (e && typeof e.currentTime === 'number') {
					this.watchProgress = e.currentTime;

					// 使用节流保存进度（每10秒最多保存一次）
					if (!this.progressSaveThrottle) {
						this.progressSaveThrottle = setTimeout(() => {
							this.fetchSaveVideoProgress();
							this.progressSaveThrottle = null;
						}, 10000);
					}
				}
			},
			formatTime(seconds) {
				if (!seconds) {
					return '';
				}
				const minutes = Math.floor(seconds / 60);
				const remainingSeconds = Math.floor(seconds % 60);
				return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
			},
			// 上传视频观看进度 在页面隐藏时请求保存到数据库
			async fetchSaveVideoProgress() {
				// 如果没有视频ID或进度，则不保存
				if (!this.curCourseMedia.id || typeof this.watchProgress !== 'number') {
					return;
				}

				try {
					// 构建请求参数
					const progressData = {
						courseMediaId: this.curCourseMedia.id,
						progress: Math.floor(this.watchProgress), 
						duration: this.videoInfo.duration ? parseInt(this.videoInfo.duration) : 0,
						watchDate: formatDate(new Date(), 'YYYY-MM-DD'),
						courseId: this.courseId
					};

					// 添加验证
					if (progressData.progress < 0 || progressData.duration < 0) {
						return;
					}

					// 只有当进度大于0时才保存
					if (progressData.progress > 0) {
						const res = await this.$http.post('/user/video/progress', progressData);
					}
				} catch (e) {
					console.error('保存进度失败:', e);
					this.showToast('保存播放进度失败', 'error');
				}
			},
			// 获取媒资信息
			async fetchCourseMedia(courseMediaId) {
				if (!courseMediaId) {
					return;
				}
				try {
					const courseMedia = await this.$http.post(`/courses/media/byId?id=${courseMediaId}`);
					if (courseMedia) {
						this.curCourseMedia = courseMedia;
						// 更新视频信息
						this.updateVideoInfo({
							id: courseMedia.id,
							title: courseMedia.title || '',
							coverUrl: courseMedia.coverImageUrl || '',
							description: courseMedia.des || '',
							createTime: courseMedia.createTime || '',
						});

						// 获取点播信息
						if (courseMedia.videoId) {
							await this.fetchVideoInfo(courseMedia.videoId);
						}
					}
				} catch (e) {
					this.showToast(e);
				}
			},
			// 获取点播信息
			async fetchVideoInfo(videoId) {
				if (!videoId) {
					throw new Error('视频ID不能为空');
				}

				try {
					const response = await this.$http.post(`/courses/media/demand?videoId=${videoId}`);
					if (!response) {
						throw new Error('视频信息不存在');
					}

					// 处理视频基础信息
					if (response.videoBase) {
						const videoBase = response.videoBase;

						this.updateVideoInfo({
							coverUrl: videoBase.coverURL || this.videoInfo.coverUrl,
							createTime: videoBase.creationTime || this.videoInfo.createTime,
							duration: videoBase.duration || '',
							mediaType: videoBase.mediaType || '',
							status: videoBase.status || '',
							title: videoBase.title || this.videoInfo.title || '暂无标题',
						});
					} else {
						throw new Error('视频信息不存在');
					}

					// 处理播放信息
					if (Array.isArray(response.playInfo) && response.playInfo.length > 0) {
						// 过滤掉无效的播放信息
						const validPlayInfo = response.playInfo.filter(info =>
							info &&
							info.playURL &&
							info.definition &&
							info.status === 'Normal' // 确保视频状态正常
						);

						if (validPlayInfo.length === 0) {
							throw new Error('没有可用的播放源');
						}

						// 按清晰度排序，优先选择高清晰度
						const sortedPlayInfo = this.sortPlayInfoByDefinition(validPlayInfo);
						// 获取可用的清晰度列表
						const definitions = sortedPlayInfo.map(info => {
							return {
								label: this.getDefinitionLabel(info.definition),
								value: info.definition,
								bitrate: this.formatBitrate(info.bitrate),
								size: this.formatSize(info.size),
								playUrl: info.playURL // 添加播放地址
							};
						});

						// 默认选择最高清晰度
						const bestQuality = sortedPlayInfo[0];
						if (!bestQuality.playURL) {
							throw new Error('视频播放地址无效');
						}

						this.updateVideoInfo({
							videoUrl: bestQuality.playURL,
							definition: bestQuality.definition,
							definitions: definitions,
							bitrate: this.formatBitrate(bestQuality.bitrate),
							size: this.formatSize(bestQuality.size)
						});
					} else {
						throw new Error('没有可用的播放信息');
					}
				} catch (e) {
					throw new Error(e.msg || '获取视频信息失败');
				}
			},
			// 更新视频信息，保持已有信息不被覆盖
			updateVideoInfo(newInfo) {
				this.videoInfo = {
					...this.videoInfo,
					...Object.fromEntries(
						Object.entries(newInfo).filter(([_, value]) => value !== null && value !== undefined &&
							value !== '')
					)
				};
			},
			// 按清晰度排序播放信息
			sortPlayInfoByDefinition(playInfo) {
				const definitionOrder = {
					'FHD': 5, // 1080P
					'HD': 4, // 高清
					'SD': 3, // 标清
					'LD': 2, // 流畅
					'AUTO': 1 // 自动
				};

				return playInfo.sort((a, b) => {
					const orderA = definitionOrder[a.definition] || 0;
					const orderB = definitionOrder[b.definition] || 0;
					return orderB - orderA;
				});
			},
			// 格式化码率
			formatBitrate(bitrate) {
				if (!bitrate) return '';
				const num = parseInt(bitrate);
				if (isNaN(num)) return bitrate;
				return `${(num / 1024).toFixed(1)}Mbps`;
			},

			// 格式化文件大小
			formatSize(size) {
				if (!size) return '';
				const num = parseInt(size);
				if (isNaN(num)) return size;
				if (num < 1024) return `${num}B`;
				if (num < 1024 * 1024) return `${(num / 1024).toFixed(1)}KB`;
				if (num < 1024 * 1024 * 1024) return `${(num / 1024 / 1024).toFixed(1)}MB`;
				return `${(num / 1024 / 1024 / 1024).toFixed(1)}GB`;
			},
			// 获取清晰度显示标签
			getDefinitionLabel(definition) {
				const labels = {
					'FHD': '1080P',
					'HD': '高清',
					'SD': '标清',
					'LD': '流畅',
					'AUTO': '自动'
				};
				return labels[definition] || definition;
			},
			// 分页加载当前课程媒资
			async fetchPageCurCourseMedia() {
				if (!this.courseId) {
					return;
				}
				try {
					const dto = {
						courseId: this.courseId,
						pageSize: this.pageSize,
						current: this.pageNumber
					};
					const courseMedias = await this.$http.post('/courses/media/list', dto);

					if (courseMedias && courseMedias.item != 0) {
						this.courseMediaList = courseMedias.items;
						this.totalMedia = courseMedias.count;
						this.pageNumber += 1;
					}
				} catch (e) {
					this.showToast(e.msg, 'error', 1000);
				}
			},
			parsedTags(tags) {
				if (!tags || tags === '') {
					return [];
				}
				return tags.split(',');
			},
			getHighestQuality() {
				if (!this.videoInfo || !this.videoInfo.definitions || this.videoInfo.definitions.length === 0) return '自动';

				const arrObj = this.videoInfo.definitions;
				// 过滤掉自动清晰度选项
				const validQualities = arrObj.filter(item => item.height > 0);

				if (validQualities.length === 0) return '自动';

				// 按height排序找出最高清晰度
				const highestQuality = validQualities.reduce((prev, current) => {
					return (prev.height > current.height) ? prev : current;
				});

				// 根据高度返回对应的清晰度标签
				if (highestQuality.height >= 1080) return '1080P';
				if (highestQuality.height >= 720) return '720P';
				if (highestQuality.height >= 480) return '480P';
				if (highestQuality.height >= 360) return '360P';

				return `${highestQuality.height}P`;
			},
			// 格式化视频时长
			formatDuration(seconds) {
				if (!seconds) return '00:00';

				// 将秒数转换为整数
				const totalSeconds = Math.floor(seconds);

				// 计算小时、分钟、秒
				const hours = Math.floor(totalSeconds / 3600);
				const minutes = Math.floor((totalSeconds % 3600) / 60);
				const remainingSeconds = totalSeconds % 60;

				// 格式化时间
				if (hours > 0) {
					// 有小时时显示 HH:MM:SS 格式
					return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
				} else {
					// 无小时时显示 MM:SS 格式
					return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
				}
			},
			formatDate(date) {
				if (!date) return '';
				const d = new Date(date);
				return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
			},
			handleError(e) {
				// 清除之前的定时器
				if (this.errorTimer) {
					clearTimeout(this.errorTimer)
				}

				// 设置错误信息
				this.errorMessage = this.formatErrorMessage(e)
				this.showError = true

				// 5秒后自动隐藏
				this.errorTimer = setTimeout(() => {
					this.showError = false
				}, 5000)
			},
			formatErrorMessage(error) {
				// 格式化错误信息
				if (error.errCode === 'HLS_BUFFER_ERROR') {
					return '视频加载异常，请检查网络'
				}
				if (error.errCode === 'RECOVERY_FAILED') {
					return '视频播放失败，请稍后重试'
				}
				switch (error.detail?.errCode) {
					case 1001:
						return '网络连接失败，请检查网络'
					case 1002:
						return '视频解码失败'
					case 1003:
						return '当前系统不支持播放该视频格式'
					case 1004:
						return '视频加载失败，请稍后重试'
					default:
						return error.errMsg || '视频播放出错，请稍后重试'
				}
			},
			// 加载课程信息
			async fetchCourse() {
				if (this.loading || !this.courseId) {
					return;
				}
				try {
					const data = await this.$http.get(`/course/info?courseId=${this.courseId}`);
					if (data) {
						this.courseInfo = data;
						this.courseInfo = {
							...this.courseInfo,
							parseTags: this.parsedTags(this.courseInfo.tags)
						};
					}
				} catch (e) {
					this.showToast(e.msg);
				}
			},
			handlePlay() {
				// 播放时隐藏错误提示
				this.showError = false
			},
			handleVideoPause() {
				// 保存播放记录
				debounce(() => {
					this.fetchSaveVideoProgress();
				}, 2000);
			},
			// 获取广告数据
			async fetchAdvertisement() {
				if (this.isLoading || !this.hasMore) return;

				try {
					this.isLoading = true;
					const response = await this.$http.get(
						`/advertisement/by/course?courseId=${this.courseId}&page=${this.pageNum}&size=${this.pageSize}`
					);

					if (response && response.items) {
						// 更新总广告列表
						this.adList = [...this.adList, ...response.items];

						// 第一页时，分配前三条给播放器
						if (this.pageNum === 1) {
							this.playerAdList = response.items.slice(0, 3);
							this.pageAdList = response.items.slice(3);
						} else {
							// 非第一页，全部添加到页面广告列表
							this.pageAdList = [...this.pageAdList, ...response.items];
						}

						// 更新分页信息
						this.hasMore = response.count > this.pageAdList.length;
						this.pageNum++;
					}
				} catch (e) {
					console.error('获取广告失败:', e);
				} finally {
					this.isLoading = false;
				}
			},
			// 获取当前媒资播放记录
			async fetchCurMediaHitory(courseMediaId) {
				try {
					const history = await this.$http.get(
						`/user/video/latest/history?courseMediaId=${courseMediaId}`);
					if (history) {
						this.mediaHistory = history;
					}
				} catch (e) {
					this.showToast('历史记录获取失败');
				}
			},
			// 处理广告点击
			handleAdClick(ad) {
				// uni.navigateTo({
				// 	url: `/subpkg/ad_detail/ad_detail?id=${ad.id}`
				// });
			},

			// 监听页面滚动到底部
			onReachBottom() {
				if (this.hasMore && !this.isLoading) {
					this.fetchAdvertisement();
				}
			},

			// 初始化数据
			async init() {
				try {
					this.loading = true;
					// 重置数据
					this.pageNum = 1;
					this.adList = [];
					this.playerAdList = [];
					this.pageAdList = [];
					this.hasMore = true;

					// 获取第一页数据
					await this.fetchAdvertisement();
					// 获取当前媒资播放记录
					await this.fetchCurMediaHitory(this.courseMediaList[0].id);
				} catch (e) {
					console.error(e);
				} finally {
					this.loading = false;
				}
			}
		},

		beforeDestroy() {
			if (this.progressSaveThrottle) {
				clearTimeout(this.progressSaveThrottle);
			}
			// 清理定时器
			if (this.errorTimer) {
				clearTimeout(this.errorTimer)
			}
			// 存储播放记录
			this.fetchSaveVideoProgress();
		},

		async onLoad(options) {
			if (options.courseId) {
				this.courseId = options.courseId;
				try {
					// 先获取课程基本信息
					await this.fetchCourse();
					// 获取课程媒资列表
					await this.fetchPageCurCourseMedia();
					
					// 判断是否有媒资信息
					if (this.courseMediaList && this.courseMediaList.length > 0) {
						// 优先使用传入的mediaId，如果没有则使用第一个媒资
						const mediaId = options.courseMediaId || this.courseMediaList[0].id;
						await this.fetchCourseMedia(mediaId);
						await this.fetchCurMediaHitory(mediaId);
					} else {
						this.showToast('课程暂无可播放内容', 'warning');
					}
					
					await this.init();
				} catch (e) {
					console.error('初始化课程失败:', e);
					this.showToast('加载课程信息失败', 'error');
				}
			} else {
				this.showToast('课程信息不完整', 'error');
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'video_pay_course_play.scss';
</style>